package com.bw.module_cinema.model.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bw.module_cinema.databinding.ItemTypePidBinding
import com.bw.module_cinema.model.adapter.TypeAdapter.OnTypeItemClickListener
import com.bw.module_cinema.model.entity.VideoTypeEntity

class NewTypeAdapter:RecyclerView.Adapter<NewTypeAdapter.NewTypeViewHolder>() {
    // 定义点击事件回调接口
    interface OnItemClickListener{
        fun onItemClick(typeid:Int)
    }

    private var listener : OnItemClickListener? = null

    // 设置点击监听器
    fun setOnItemClickListener(listener : OnItemClickListener){
        this.listener = listener
    }

    private var list : List<VideoTypeEntity> = emptyList()

    // 1. 定义DiffUtil回调
    private val diffCallback = object : DiffUtil.ItemCallback<VideoTypeEntity>() {
        override fun areItemsTheSame(oldItem: VideoTypeEntity, newItem: VideoTypeEntity): Boolean {
            // 用唯一标识判断是否为同一个item（如id）
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: VideoTypeEntity, newItem: VideoTypeEntity): Boolean {
            // 判断内容是否相同（避免无意义刷新）
            return oldItem == newItem // 若TypeData是数据类，可直接用 ==
        }
    }

    // 2. 提供更新数据的方法
    fun updateData(newList: List<VideoTypeEntity>) {
        val diffResult = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
            override fun getOldListSize() = list.size
            override fun getNewListSize() = newList.size
            override fun areItemsTheSame(oldPos: Int, newPos: Int) =
                list[oldPos].id == newList[newPos].id
            override fun areContentsTheSame(oldPos: Int, newPos: Int) =
                list[oldPos] == newList[newPos]
        })
        Log.d("NewTypeAdapter", "接收数据总数：${newList.size}")
        list = newList.toList()
        diffResult.dispatchUpdatesTo(this) // 局部刷新
    }

    fun setData(mList: List<VideoTypeEntity>){
        list = mList.toList()
        notifyDataSetChanged()
    }

    class NewTypeViewHolder(
        val binding:ItemTypePidBinding
    ):RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): NewTypeViewHolder {
        val binding = ItemTypePidBinding.inflate(LayoutInflater.from(parent.context),parent,false)
        return NewTypeViewHolder(binding)
    }

    override fun onBindViewHolder(holder: NewTypeViewHolder, position: Int) {
        val item = list[position]
        holder.binding.type = item

        holder.itemView.setOnClickListener {
            listener?.onItemClick(item.id)
        }
    }

    override fun getItemCount(): Int {
        Log.d("NewTypeAdapter", "展示条目数：${list.size}")
        return list.size
    }

}